package lyf.framework.web.handler;

import lyf.framework.web.mvc.Controller;
import lyf.framework.web.mvc.RequestMapping;
import lyf.framework.web.mvc.RequestParam;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;

public class HandlerManager {
	/**
	 * 存储找到的可以用的handler
	 */
	public static List<MappingHandler> mappingHandlerList = new ArrayList<>();

	/**
	 * 初始化处理器映射器
	 */
	public static void resolveMappingHandler(List<Class<?>> classList) {
		classList.forEach(cls -> {
			if (cls.isAnnotationPresent(Controller.class)) {
				parseHandlerFromController(cls);
			}
		});
	}

	private static void parseHandlerFromController(Class<?> cls) {
		Method[] methods = cls.getMethods();
		for (Method method : methods) {
			if (method.isAnnotationPresent(RequestMapping.class)) {
				String uri = method.getAnnotation(RequestMapping.class).value();
				List<String> paramNameList = new ArrayList<>();
				for (Parameter parameter : method.getParameters()) {
					if (parameter.isAnnotationPresent(RequestParam.class)) {
						paramNameList.add(parameter.getAnnotation(RequestParam.class).value());
					}
				}
				String[] params = paramNameList.toArray(new String[paramNameList.size()]);
				MappingHandler mappingHandler = new MappingHandler(uri, method, cls, params);
				HandlerManager.mappingHandlerList.add(mappingHandler);
			}
		}
	}
}
